package com.bls.lib.permission;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 6.0Dynamic authorization application
 * Created by Administrator on 2016/8/26.
 */
class PermissionUtil {

    static void checkPermission(final Activity activity, final String[] permissions, PermissionInterface permissionInterface) {
        if (Build.VERSION.SDK_INT < 23) {
            permissionInterface.success();
            return;
        }
        final List<String> deniedPermissions = findDeniedPermissions(activity, permissions);
        if (deniedPermissions != null && deniedPermissions.size() > 0) {
            permissionInterface.fail(deniedPermissions);
        } else {
            permissionInterface.success();
        }
    }


    static void requestContactsPermissions(final Activity activity, final String[] permissions, final int requestCode) {
        if (shouldShowPermissions(activity, permissions)) {
            ActivityCompat.requestPermissions(activity, permissions, requestCode);
        } else {
            ActivityCompat.requestPermissions(activity, permissions, requestCode);
        }
    }

    static boolean verifyPermissions(int[] grantResults) {
        if (grantResults.length < 1) {
            return false;
        }
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    public interface PermissionInterface {
        void success();
        void fail(List<String> permissions);
    }

    private static List<String> findDeniedPermissions(Activity activity, String... permission) {
        List<String> denyPermissions = new ArrayList<>();
        for (String value : permission) {
            if (ContextCompat.checkSelfPermission(activity, value) != PackageManager.PERMISSION_GRANTED) {
                denyPermissions.add(value);
            }
        }
        return denyPermissions;
    }


    static boolean shouldShowPermissions(Activity activity, String... permission) {
        for (String value : permission) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, value)) {
                return true;
            }
        }
        return false;
    }
}
